﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public class CustomersCollection : AbstractCollection
    {
        ///// <summary>
        ///// Дилеры
        ///// </summary>
        //private List<Customers> _dealers;


        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        protected static List<Customers> _list;

        /// <summary>
        /// Дилеры
        /// </summary>
        private static List<Customers> _dealers;

        /// <summary>
        /// Список всех клиентов
        /// </summary>
        public List<Customers> CustomersList
        {
            get
            {
                return Entities.Customers.ToList();
                if (_list == null)
                    _list = DB.Entities.Customers.ToList();
                return _list;
            }
        }

        /// <summary>
        /// Список активных клиентов
        /// </summary>
        public List<Customers> ActiveCustomers
        {
            get { return CustomersList.Where(c => c.IsActive != null && (bool) c.IsActive).ToList(); }
        }

        /// <summary>
        /// Дилеры
        /// </summary>
        public static List<Customers> Dealers
        {
            get
            {
                if (_dealers == null)
                {
                    var col = new CustomersCollection();

                    var result = new List<Customers>();

                    var dealersNumbers = new[]
                                             {
                                                 450, 861, 221, 432, 435, 456, 1593, 422, 1529, 5179, 1279, 1121, 426,
                                                 4311
                                                 , 4249, 4257, 4832, 156, 900, 4249, 861, 7459, 6064, 458, 5118, 7502,
                                                 1401
                                                 , 7699, 4257, 7699, 4257, 7557, 7828, 8450, 8615, 4257, 7675, 7828,
                                                 4307, 900, 4311
                                             };


                    foreach (int number in dealersNumbers)
                    {
                        Customers cust = col.GetCustomerBySequentalNumber(number);
                        if (cust != null)
                            if (!result.Contains(cust))
                                result.Add(cust);
                    }


                    _dealers = result;
                }
                return _dealers;
            }
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            _list = null;
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return _list;
        }

        /// <summary>
        /// Получение элемента из коллекции по идентификатору
        /// </summary>
        /// <param name="itemId">Идентификатор</param>
        /// <returns>Элемент</returns>
        public override object GetItemById(int itemId)
        {
            return Entities.Customers.Find(itemId);
        }

        /// <summary>
        /// Получение клиента по номеру САП
        /// </summary>
        /// <param name="SAPnumber">Номер САП</param>
        /// <returns>Клиент</returns>
        public Customers GetCustomerBySAPNumber(int SAPnumber)
        {
            return CustomersList.FirstOrDefault(c => c.NumberInSAP == SAPnumber);
        }


        /// <summary>
        /// Получение клиента по клиентскому номеру
        /// </summary>
        /// <param name="number">Клиентский номер</param>
        /// <returns>Клиент</returns>
        public Customers GetCustomerBySequentalNumber(int number)
        {
            return CustomersList.FirstOrDefault(c => c.SequentialNumber == number);
        }


        /// <summary>
        /// Поиск дилера по названию юридического лица
        /// </summary>
        /// <param name="dealerName">Название юридического лица дилера</param>
        /// <param name="exactName">Искать полное совпадение?</param>
        /// <returns>Найденный дилер</returns>
        public Customers GetDealerByName(string dealerName, bool exactName = true)
        {
            Customers result = null;


            if (exactName)
            {
                foreach (Customers dealer in Dealers)
                {
                    if (dealer.LegalEntities.Any(legalEntity => legalEntity.Name == dealerName))
                    {
                        result = dealer;
                        break;
                    }
                }
            }
            else
            {
                foreach (Customers dealer in Dealers)
                {
                    foreach (LegalEntities legalEntity in dealer.LegalEntities)
                    {
                        if (legalEntity.Name.Trim().ToUpper() == dealerName.Trim().ToUpper())
                        {
                            result = dealer;
                            break;
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Удаление клиента
        /// </summary>
        /// <param name="customer">Клиент для удаления</param>
        /// <returns>Результат операции</returns>
        public bool Delete(Customers customer)
        {
            var leCol = new LegalEntitiesCollection();

            foreach(var le in customer.LegalEntities)
            {
                leCol.Delete(le);
            }


            var cust = Entities.Customers.Find(customer.IdCustomer);
             return base.Delete(cust);

            //DeleteById(customer.IdCustomer);

            

          //  return true;
        }

        /// <summary>
        /// Поиск дилера по названию юридического лица
        /// </summary>
        /// <param name="dealerName">Название юридического лица дилера</param>
        /// <param name="exactName">Искать полное совпадение?</param>
        /// <returns>Найденный дилер</returns>
        public LegalEntities GetDealerLegalEntityByName(string dealerName, bool exactName = true)
        {
            LegalEntities result = null;


            if (exactName)
            {
                foreach (Customers dealer in Dealers)
                {
                    foreach (LegalEntities legalEntity in dealer.LegalEntities)
                    {
                        if (legalEntity.Name == dealerName)
                        {
                            result = legalEntity;
                            break;
                        }
                    }
                }
            }
            else
            {
                foreach (Customers dealer in Dealers)
                {
                    foreach (LegalEntities legalEntity in dealer.LegalEntities)
                    {
                        if (legalEntity.Name.Trim().ToUpper() == dealerName.Trim().ToUpper())
                        {
                            result = legalEntity;
                            break;
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Добавление клиента
        /// </summary>
        /// <param name="item">Клиент</param>
        /// <param name="userLoginName">Имя пользователя</param>
        /// <returns>Результат добавления клиента</returns>
        public new bool Add(object item, string userLoginName)
        {
            var customer = item as Customers;
            if (customer == null)
                return false;


            customer.SaveTime = DateTime.Now;
            customer.IsActive = true;
            customer.SequentialNumber = Customers.MaxCustomerSequentalNumber + 1;

            if (base.Add(customer, userLoginName))
            {
                var le = new LegalEntities {Name = customer.Name, IdCustomer = customer.IdCustomer, IsActive = true};
                var leCol = new LegalEntitiesCollection();

                return leCol.Add(le, userLoginName);
            }

            return false;
        }




        /// <summary>
        /// Слияние двух клиентов
        /// </summary>
        /// <param name="badCustomerNumber">Номер первого клиента</param>
        /// <param name="goodCustomerNumber">Номер второго клиента</param>
        /// <returns></returns>
        public bool CustomersMerging(int badCustomerNumber,int goodCustomerNumber)
        {
            var firstCustomer = GetCustomerBySequentalNumber(badCustomerNumber);
            var secondCustomer = GetCustomerBySequentalNumber(goodCustomerNumber);

            if(firstCustomer==null || secondCustomer==null)
                return false;
                        else
            {
               // var leCol = new LegalEntitiesCollection();

                for (int index = 0; index < firstCustomer.LegalEntities.ToList().Count; index++)
                {
                    var le = firstCustomer.LegalEntities.ToList()[index];
                    le.IdCustomer = secondCustomer.IdCustomer;
                    le.Customers = secondCustomer;
                    Save();
                   // leCol.Update(le , "Max" + DateTime.Now);
                }


              //  var techCol = new TechnicRequestsCollection();
                  foreach(var item in firstCustomer.TechnicRequests.ToList())
                  {
                      item.IdCustomer = secondCustomer.IdCustomer;
                      item.Customers = secondCustomer;
                    //  techCol.Update(item, "Max" + DateTime.Now);
                      Save();
                  }

                var col = new CustomersEquipmentsCollection();

                foreach(var item in col.CustomersEquipmentsList.Where(c=>c.IdCustomer==firstCustomer.IdCustomer))
                {
                    item.IdCustomer = secondCustomer.IdCustomer;
                    item.Customers = secondCustomer;
                    col.Update(item, "Max" + DateTime.Now);
                  //  Save();
                }

                var cc = col.CustomersEquipmentsList.Where(c => c.IdCustomer == firstCustomer.IdCustomer);

                Delete(firstCustomer);




                return true;
}
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin)
        {
            var newCustomer = (Customers) item;

            if (newCustomer == null)
                return false;

            var customer4Update = (Customers) GetItemById(newCustomer.IdCustomer);
            if (customer4Update == null)
                return false;


            if (!string.IsNullOrEmpty(newCustomer.Comments))
                customer4Update.Comments = newCustomer.Comments;

            if (newCustomer.DateStartProfineRUS > DateTime.MinValue)
            {
                customer4Update.DateStartProfineRUS = newCustomer.DateStartProfineRUS;
            }


            if (newCustomer.IdCustomerClassificationsByBusiness != null)
                customer4Update.IdCustomerClassificationsByBusiness = newCustomer.IdCustomerClassificationsByBusiness;

            if (newCustomer.IdCustomerClassificationsProfine != null)
                customer4Update.IdCustomerClassificationsProfine = newCustomer.IdCustomerClassificationsProfine;
            if (newCustomer.IdCustomerClassificationsTurnover != null)
                customer4Update.IdCustomerClassificationsTurnover = newCustomer.IdCustomerClassificationsTurnover;

            if (newCustomer.IdManager != null) customer4Update.IdManager = newCustomer.IdManager;

            if (newCustomer.IdprofineRegion != null) customer4Update.IdprofineRegion = newCustomer.IdprofineRegion;

            if (newCustomer.IsActive != null) customer4Update.IsActive = newCustomer.IsActive;

            if (!string.IsNullOrEmpty(newCustomer.Name)) customer4Update.Name = newCustomer.Name;

            if (newCustomer.NumberInSAP != null) customer4Update.NumberInSAP = newCustomer.NumberInSAP;

            customer4Update.SaveTime = DateTime.Now;


            return base.Update(customer4Update, userLogin);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(CustomersList);
        }

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (Customers);
        }

        #endregion
    }
}